<template>
  <a-form
    :model="userForm"
    :rules="rules"
    layout="vertical"
    ref="userFormRef"
    @finish="handleUpdate"
  >
    <a-row :gutter="16">
      <a-col :span="12">
        <a-form-item label="用户ID" name="id">
          <a-input v-model:value="userForm.id" disabled />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="角色">
          <a-input :value="userRole" disabled />
        </a-form-item>
      </a-col>
    </a-row>
    
    <a-row :gutter="16">
      <a-col :span="12">
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="userForm.username" placeholder="请输入用户名" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="头像" name="avatar">
          <div class="avatar-wrapper">
            <a-avatar :size="64" :src="userForm.avatar || defaultAvatar" />
            <a-input v-model:value="userForm.avatar" placeholder="请输入头像URL" />
          </div>
        </a-form-item>
      </a-col>
    </a-row>
    
    <a-row :gutter="16">
      <a-col :span="12">
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="userForm.email" placeholder="请输入邮箱" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="userForm.phone" placeholder="请输入手机号" />
        </a-form-item>
      </a-col>
    </a-row>
    
    <a-row :gutter="16">
      <a-col :span="12">
        <a-form-item label="性别" name="gender">
          <a-radio-group v-model:value="userForm.gender">
            <a-radio :value="0">女</a-radio>
            <a-radio :value="1">男</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="出生日期" name="birthDate">
          <a-date-picker 
            v-model:value="birthDate" 
            style="width: 100%"
            :locale="zhCN"
            format="YYYY-MM-DD"
          />
        </a-form-item>
      </a-col>
    </a-row>
    
    <a-row>
      <a-col :span="24" style="text-align: center">
        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="loading">
            保存修改
          </a-button>
          <a-button style="margin-left: 8px" @click="resetForm">
            重置
          </a-button>
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import zhCN from 'ant-design-vue/es/date-picker/locale/zh_CN';
import { useUserStore } from '@/stores/user';
import { getLoginUserInfo, updateUserInfo } from '@/api/user';
import dayjs from 'dayjs';

// 默认头像
const defaultAvatar = 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png';
// 加载状态
const loading = ref(false);
// 表单引用
const userFormRef = ref(null);
// 用户信息store
const userStore = useUserStore();
// 出生日期
const birthDate = ref(null);

// 用户表单数据
const userForm = reactive({
  id: '',
  username: '',
  email: '',
  phone: '',
  avatar: '',
  gender: 1,
  role: 0,
  status: 1
});

// 计算属性：用户角色名称
const userRole = computed(() => {
  return userForm.role === 1 ? '管理员' : '普通用户';
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度必须在3-20个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
};

// 初始化用户信息
const initUserInfo = async () => {
  try {
    loading.value = true;
    const userData = await getLoginUserInfo();
    
    // 填充表单数据
    Object.keys(userForm).forEach(key => {
      if (userData[key] !== undefined) {
        userForm[key] = userData[key];
      }
    });
    
    // 处理出生日期
    if (userData.birthDate) {
      birthDate.value = dayjs(userData.birthDate);
    }
    
    loading.value = false;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    message.error('获取用户信息失败');
    loading.value = false;
  }
};

// 处理更新用户信息
const handleUpdate = async (values) => {
  try {
    loading.value = true;
    
    // 构建更新数据
    const updateData = { ...values };
    
    // 处理出生日期
    if (birthDate.value) {
      updateData.birthDate = birthDate.value.format('YYYY-MM-DD');
    }
    
    // 调用更新API
    const updatedUser = await updateUserInfo(updateData);
    
    // 更新本地存储的用户信息
    userStore.setUser(updatedUser);
    
    message.success('个人信息更新成功');
    loading.value = false;
  } catch (error) {
    console.error('更新用户信息失败:', error);
    message.error('更新用户信息失败: ' + (error.message || '未知错误'));
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  userFormRef.value?.resetFields();
  initUserInfo();
};

// 组件挂载时获取用户信息
onMounted(() => {
  initUserInfo();
});
</script>

<style scoped>
.avatar-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}
</style> 